package myomi.funf;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Function {
	private Object instance;
	private Method method;
	private List<String> argNames;
	private String returnName;
	
	public Function(String className, String methodName, List<String> argNames, String returnName) {
		try {
			Class<?> clazz = Class.forName(className);
			this.instance = clazz.newInstance();
			for (Method m: clazz.getDeclaredMethods()) {
				if (m.getName().equals(methodName)) {
					this.method = m;
				}
			}
			this.argNames = argNames;
			this.returnName = returnName;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	public void execute(Context context) {
		Map<String, Object> variables = context.getVariables();
		
		List<Object> args = new ArrayList<Object>();
		for (String n: argNames) {
			args.add(variables.get(n));
		}
		
		try {
			Object result = method.invoke(instance, args.toArray());
			variables.put(returnName, result);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}
